<!--
  * 订单管理列表
  *
  * @Author:    1024创新实验室-主任：卓大
  * @Date:      2022-09-03 21:35:00
  * @Wechat:    zhuda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="关键字" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.orderNo" placeholder="订单号/物流单号" />
      </a-form-item>

      <a-form-item label="手机号" class="smart-query-form-item">
        <a-input style="width: 150px" v-model:value="queryForm.phone" placeholder="娃娘手机号" />
      </a-form-item>

      <a-form-item label="绑定状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.bindStatus" style="width: 120px" placeholder="请选择">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="1">已绑定</a-select-option>
          <a-select-option value="0">未绑定</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="创建时间" class="smart-query-form-item">
        <a-range-picker v-model:value="createDate" :presets="defaultTimeRanges" @change="createDateChange" style="width: 260px" />
      </a-form-item>

      <a-form-item class="smart-query-form-item smart-margin-left10">


        <a-button type="primary" @click="onSearch">
            <template #icon>
              <SearchOutlined />
            </template>
            查询
          </a-button>

          <a-divider type="vertical" />

          <a-button type="primary" @click="importExcel">
          <template #icon>
            <UploadOutlined />
          </template>
          导入Excel
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>

  <a-card size="small" :bordered="false">
    <a-table
      :columns="columns"
      :data-source="tableData"
      :pagination="false"
      :loading="loading"
      size="middle"
      bordered
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'bindStatus'">
          <span :style="{ color: record.bindStatus === 1 ? '#52c41a' : '#ff4d4f' }">
            {{ record.bindStatus === 1 ? '已绑定' : '未绑定' }}
          </span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a v-if="record.bindStatus === 1" @click="viewAlbum(record)">用户相册</a>
          <a-divider type="vertical" />
          <a @click="editOrder(record)">编辑</a>
        </template>

      </template>
    </a-table>

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNum"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryOrderList"
        @showSizeChange="queryOrderList"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <OrderEditModal ref="orderEditModalRef" @success="handleEditSuccess" />
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined, UploadOutlined } from '@ant-design/icons-vue';
import OrderEditModal from './components/order-edit-modal.vue';
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from '/@/constants/common-const';
import { defaultTimeRanges } from '/@/lib/default-time-ranges';
import { orderApi } from '/@/api/business/bjd/order-api';

// 编辑模态框引用
const orderEditModalRef = ref();
const router = useRouter();



// 查询表单数据
const queryForm = reactive({
  pageNum: 1,
  pageSize: PAGE_SIZE,
  keywords: '',
  phone: '',
  bindStatus: '',
  startTime: null,
  endTime: null,
});

// 表格列定义
const columns = [
  {
    title: '订单号',
    dataIndex: 'orderNo',
    width: 180,
  },
  {
    title: '物流单号',
    dataIndex: 'logisticsNo',
    width: 180,
  },
  {
    title: '娃娃ID',
    dataIndex: 'dollNo',
    width: 180,
  },
  {
    title: '娃娘姓名',
    dataIndex: 'dollName',
    width: 120,
  },
  {
    title: '娃娘手机',
    dataIndex: 'dollPhone',
    width: 120,
  },
  {
    title: '绑定微信',
    dataIndex: 'bindStatus',
    width: 100,
  },
  {
    title: '自定义昵称',
    dataIndex: 'bindDollNickName',
    width: 120,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    width: 100,
    fixed: 'right',
  },
];

// 表格数据
const tableData = ref([]);
const total = ref(0);
const loading = ref(false);
const createDate = ref([]);

// 日期选择改变
const createDateChange = (dates, dateStrings) => {
  queryForm.startTime = dateStrings[0] + ' 00:00:00';
  queryForm.endTime = dateStrings[1] + ' 23:59:59';
};

// 查询
const onSearch = () => {
  queryForm.pageNum = 1;
  queryOrderList();
};

// 重置
const resetQuery = () => {
  queryForm.keywords = '';
  queryForm.phone = '';
  queryForm.bindStatus = '';
  queryForm.startTime = null;
  queryForm.endTime = null;
  createDate.value = [];
  onSearch();
};

// 导入Excel
const importExcel = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.accept = '.xlsx,.xls';
  input.onchange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    
    const formData = new FormData();
    formData.append('file', file);
    
    try {
      loading.value = true;
      const res = await orderApi.import(formData);
      if (res.ok) {
        message.success('导入成功');
        queryOrderList();
      }
    } catch (error) {
      message.error('导入失败：' + (error.message || '未知错误'));
    } finally {
      loading.value = false;
    }
  };
  input.click();
};

// 查看相册
const viewAlbum = (record) => {
  router.push({
    path: '/user/user-photos-list',
    query: {
      orderNo: record.orderNo
    }
  });
};

// 编辑订单
const editOrder = (record) => {
  orderEditModalRef.value.open(record);
};

// 编辑成功回调
const handleEditSuccess = () => {
  queryOrderList();
};

// 获取订单列表数据
const queryOrderList = async () => {
  loading.value = true;
  try {
    const res = await orderApi.queryPage(queryForm);
    if (res.data) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    }
  } catch (error) {
    message.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  queryOrderList();
});
</script>